//
//  ChatInputView.m
//  YunShouHu
//
//  Created by WangQiang on 16/6/19.
//  Copyright © 2016年 WangQiang. All rights reserved.
//

#import "ChatMsgInputView.h"
#import "EmojiView.h"
#import "WQEdgeTitleButton.h"
#import "MoreInputView.h"

#import "EmojiAttachment.h"
#import "EmojiInputDelegate.h"
#import "MsgVoiceRecordButton.h"


//输入框最大高度
#define kMaxHeightTextView   (134)

//默认输入框和父控件底部间隔
#define kDefaultBottomTextView_SupView  (8)

#define kDefaultTopTextView_SupView  (8)
#define kMinBarHeight 56
//输入框的最小距离
#define kMinHeightTextView (kMinBarHeight-kDefaultBottomTextView_SupView - kDefaultTopTextView_SupView)

@interface ChatMsgInputView()<UITextViewDelegate,EmojiInputDelegate,MoreInputViewDelegate,MsgVoiceRecordDelegate>{
        /**
         *  @brief  TextView和自己底部约束，会被动态增加、删除
         */
        NSLayoutConstraint *mBottomConstraintTextView;
        
        
        /**
         *  @brief  自己和父控件 底部约束，使用这个约束让自己伴随键盘移动
         */
        NSLayoutConstraint *mBottomConstraintWithSupView;
        
        /**
         *  @brief  TextView的高度
         */
        CGFloat mHeightTextView;
    
        EmojiView *mEmojiView;
        MoreInputView *mMoreView;
        MsgVoiceRecordButton *mVoiceRecordBtn;
    
}

@property (weak ,nonatomic) UIButton *emojiBtn;
@property (weak ,nonatomic) UIButton *moreBtn;
@property (weak ,nonatomic) UIButton *voiceBtn;
@end
@implementation ChatMsgInputView
+(instancetype)chartInputView{
    return [[self alloc] init];
}
-(instancetype)init{
    if(self = [super init]){
        
        //添加
        KDImageTextView *textView = [[KDImageTextView alloc] init];
        textView.font = MYFont(17.0);
        self.backgroundColor = [UIColor lightGrayColor];
        textView.textColor = [UIColor lightTextColor];
        textView.delegate = self;
        textView.translatesAutoresizingMaskIntoConstraints = NO;
//        textView.layoutMargins = UIEdgeInsetsMake(0.0, 8.0, 10.0, 8.0);
        textView.contentInset = UIEdgeInsetsZero;
        textView.scrollEnabled = NO;
        textView.scrollsToTop = NO;
        textView.returnKeyType = UIReturnKeySend;
        [textView addCornerRadius:5.0];
        _inputView = textView;
        [self addSubview:textView];
        
        UIButton *voiceBtn = [[UIButton alloc] init];
        [voiceBtn addTarget:self action:@selector(voiceAction:) forControlEvents:UIControlEventTouchUpInside];
        [voiceBtn setImage:[UIImage imageNamed:@"chatting_setmode_voice_btn_normal"] forState:UIControlStateNormal];
        [voiceBtn setImage:[UIImage imageNamed:@"chatting_setmode_msg_btn_focused"] forState:UIControlStateSelected];
        voiceBtn.translatesAutoresizingMaskIntoConstraints = NO;
        self.voiceBtn = voiceBtn;
        [self addSubview:voiceBtn];
        
        
        UIButton *faceBtn = [[UIButton alloc] init];
        [faceBtn setImage:[UIImage imageNamed:@"chat_face_btn_pressed"] forState:UIControlStateNormal];
        [faceBtn setImage:[UIImage imageNamed:@"chatting_setmode_msg_btn_focused"] forState:UIControlStateSelected];
        faceBtn.translatesAutoresizingMaskIntoConstraints = NO;
        [faceBtn addTarget:self action:@selector(emojiAction:) forControlEvents:UIControlEventTouchUpInside];
        self.emojiBtn = faceBtn;
        [self addSubview:faceBtn];
        
        UIButton *moreBtn = [[UIButton alloc] init];
        [moreBtn setImage:[UIImage imageNamed:@"chat_add_btn_pressed"] forState:UIControlStateNormal];
        [moreBtn setImage:[UIImage imageNamed:@"chatting_setmode_msg_btn_focused"] forState:UIControlStateSelected];
        moreBtn.translatesAutoresizingMaskIntoConstraints = NO;
        [moreBtn addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
        self.moreBtn = moreBtn;
        [self addSubview:moreBtn];
        
        NSDictionary *views = [NSDictionary dictionaryWithObjectsAndKeys:textView,@"textView",moreBtn,@"moreBtn",faceBtn,@"faceBtn",voiceBtn,@"voiceBtn", nil];
        NSDictionary *metrics = @{@"btnW":@40,@"btnH":@40,@"paddingH":@0,@"paddingTop":@((kMinBarHeight - 40)*0.5),@"paddingLeft":@5};
        NSArray *textViewHConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-paddingLeft-[voiceBtn(btnW)]-paddingH-[textView]-paddingH-[faceBtn(btnW)]-paddingH-[moreBtn(btnW)]-paddingLeft-|" options:0 metrics:metrics views:views];
        NSArray *textViewVConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[textView]-8-|" options:0 metrics:metrics views:views];
        mBottomConstraintTextView = [textViewVConstraints lastObject];
        [self addConstraints:textViewHConstraint];
        [self addConstraints:textViewVConstraints];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-paddingTop-[voiceBtn(btnH)]" options:0 metrics:metrics views:views]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-paddingTop-[faceBtn(btnH)]" options:0 metrics:metrics views:views]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-paddingTop-[moreBtn(btnH)]" options:0 metrics:metrics views:views]];
        
        
        /**
         *  @brief  监听键盘显示、隐藏变化，让自己伴随键盘移动
         */
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//获取自己和父控件底部约束，控制该约束可以让自己伴随键盘移动
-(void)updateConstraints
{
    [super updateConstraints];
    
    
    if (!mBottomConstraintWithSupView)
    {
        NSArray *constraints = self.superview.constraints;
        
        for (int index= (int)constraints.count-1; index>0; index--)
        {//从末尾开始查找
            NSLayoutConstraint *constraint = constraints[index];
            
            if ((constraint.firstItem == self || constraint.secondItem == self) && constraint.firstAttribute == NSLayoutAttributeBottom && constraint.secondAttribute == NSLayoutAttributeBottom)
            {//获取自己和父控件底部约束
                mBottomConstraintWithSupView = constraint;
                
                break;
            }
        }
    }
    
}

/**
 *  @brief  返回自己的固有内容尺寸，刷新固有内容尺寸系统将会重新调用此方法
 *
 *  @return 宽度不设置固有内容尺寸，只设置高度
 */
-(CGSize)intrinsicContentSize
{
    CGFloat height = mHeightTextView+kDefaultBottomTextView_SupView +kDefaultTopTextView_SupView;
    
    height += [mMoreView intrinsicContentSize].height; //如果更多视图当前正在显示，需要加上更多视图的高度
    
    height += [mEmojiView intrinsicContentSize].height; //如果表情视图当前正在显示，需要加上他的的高度
    height = MAX(kMinHeightTextView + kDefaultTopTextView_SupView + kDefaultBottomTextView_SupView, height);
      return CGSizeMake(UIViewNoIntrinsicMetric, height);
}

-(instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        
    }
    return self;
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    [self clearKeyBoard];
    return YES;
}


-(void)textViewDidChange:(UITextView *)textView{
    //计算输入框最小高度
    CGSize size =  [textView sizeThatFits:CGSizeMake(textView.contentSize.width, 0)];
    
    CGFloat contentHeight;
    
    //输入框的高度不能超过最大高度
    if (size.height > kMaxHeightTextView)
    {
        contentHeight = kMaxHeightTextView;
        textView.scrollEnabled = YES;
    } else
    {
        contentHeight = size.height;
        textView.scrollEnabled = NO;
    }
    if(contentHeight < kMinHeightTextView) contentHeight = kMinHeightTextView;
    
    if (mHeightTextView != contentHeight)
    {//如果当前高度需要调整，就调整，避免多做无用功
        mHeightTextView = contentHeight ;//重新设置自己的高度
        [self invalidateIntrinsicContentSize];
    }

}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        [self sendMessage];
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}
-(void)keyboardChange:(NSNotification *)note{
 
    // 1.键盘弹出需要的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 取出键盘高度
    CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (CGRectIsNull(keyboardF)) {
        return;
    }
    CGFloat keyboardH = keyboardF.size.height;
    UIViewAnimationCurve animationCurve = [note.userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
    UIViewAnimationOptions animationOptions = UIViewAnimationOptionBeginFromCurrentState;
    if (animationCurve == UIViewAnimationCurveEaseIn) {
        animationOptions |= UIViewAnimationOptionCurveEaseIn;
    }
    else if (animationCurve == UIViewAnimationCurveEaseInOut) {
        animationOptions |= UIViewAnimationOptionCurveEaseInOut;
    }
    else if (animationCurve == UIViewAnimationCurveEaseOut) {
        animationOptions |= UIViewAnimationOptionCurveEaseOut;
    }
    else if (animationCurve == UIViewAnimationCurveLinear) {
        animationOptions |= UIViewAnimationOptionCurveLinear;
    }
   
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:animationCurve];
    
    if (note.name == UIKeyboardWillShowNotification)
    {
        mBottomConstraintWithSupView.constant = keyboardH;
    }else
    {
        mBottomConstraintWithSupView.constant = 0;
    }
    
    [self.superview layoutIfNeeded];
    [UIView commitAnimations];
}

-(void)clearKeyBoard{
    if(self.inputView.isFirstResponder){
        [self.inputView resignFirstResponder];
    }
    [self removeVoiceView];
    [self removeEmojiView];
    [self removeMoreView];
}
#pragma mark -- 动作
-(void)removeVoiceView{
    if(mVoiceRecordBtn){
        [mVoiceRecordBtn removeFromSuperview];
        mVoiceRecordBtn = nil;
        mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
        [self invalidateIntrinsicContentSize];
        self.voiceBtn.selected = NO;
    }
}
- (void)voiceAction:(UIButton *)sender {
    if (mMoreView)
    {//如果当前还在显示更多视图，则隐藏他先
        [self moreAction:self.moreBtn];
    }
    if (mEmojiView)
    {//如果当前还在显示更多视图，则隐藏他先
        [self emojiAction:self.emojiBtn];
    }
    
    if (sender.selected)
    {
//        [mVoiceRecordBtn removeFromSuperview];
//        mVoiceRecordBtn = nil;
//        
//        mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
        [self removeVoiceView];
        [self textViewDidChange:self.inputView];
        [self.inputView becomeFirstResponder];
    }else
    {
           [self.inputView resignFirstResponder];
        mVoiceRecordBtn = [[MsgVoiceRecordButton alloc] initVocieRecordButton];
        mVoiceRecordBtn.delegate = self;

        [self addSubview:mVoiceRecordBtn];
        mVoiceRecordBtn.translatesAutoresizingMaskIntoConstraints  = NO;
        [self addConstraint:[NSLayoutConstraint constraintWithItem:mVoiceRecordBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.inputView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:mVoiceRecordBtn attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.inputView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:mVoiceRecordBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.inputView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:mVoiceRecordBtn attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.inputView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            for (NSLayoutConstraint *constraint in self.inputView.constraints) {
                if(constraint.firstAttribute == NSLayoutAttributeHeight){
                    constraint.constant = kMinHeightTextView;
                    mHeightTextView = kMinHeightTextView ;//重新设置自己的高度
                }
            }
            
            
            mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
            
            [self invalidateIntrinsicContentSize];
        });
         sender.selected = !sender.selected;
    }
    
}
-(void)removeEmojiView{
    [mEmojiView removeFromSuperview];
    mEmojiView = nil;
    mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
    [self invalidateIntrinsicContentSize];
    self.emojiBtn.selected = NO;

}

- (void)emojiAction:(UIButton *)sender {
    if (mMoreView)
    {//如果当前还在显示更多视图，则隐藏他先
        [self moreAction:self.moreBtn];
    }
//
    if(mVoiceRecordBtn){
        [self voiceAction:self.voiceBtn];
    }
    
    if (sender.selected)
    {
//        [mEmojiView removeFromSuperview];
//        mEmojiView = nil;
//        
//        mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
        [self removeEmojiView];
        [self.inputView becomeFirstResponder];
    }else
    {
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        mEmojiView = [EmojiView emojiView];
        mEmojiView.delegate = self;
        [self addSubview:mEmojiView];
        mEmojiView.translatesAutoresizingMaskIntoConstraints  = NO;
           NSDictionary *metrics = @{@"bottomToInputView":@kDefaultBottomTextView_SupView};
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[emojiView]-0-|" options:0 metrics:nil views:@{@"emojiView":mEmojiView}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[inputView]-bottomToInputView-[emojiView]" options:0 metrics:metrics views:@{@"emojiView":mEmojiView,@"inputView":self.inputView}]];
        
        mBottomConstraintTextView.constant = (kDefaultBottomTextView_SupView+[mEmojiView intrinsicContentSize].height);
        [self.inputView resignFirstResponder];
        [CATransaction commit];
        [self invalidateIntrinsicContentSize];
        
        sender.selected = !sender.selected;
    }
    
   
    
}
-(void)removeMoreView{
    [mMoreView removeFromSuperview];
    mMoreView = nil;
    mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
    [self invalidateIntrinsicContentSize];
    self.moreBtn.selected = NO;
}
-(void)moreAction:(UIButton *)sender{
    if (mEmojiView)
    {//如果当前还在显示更多视图，则隐藏他先
        [self emojiAction:self.emojiBtn];
    }
    if(mVoiceRecordBtn){
        [self voiceAction:self.voiceBtn];
    }
    //
    if (sender.selected)
    {
//        [mMoreView removeFromSuperview];
//        mMoreView = nil;
//        mBottomConstraintTextView.constant = kDefaultBottomTextView_SupView;
        [self removeMoreView];
        [self.inputView becomeFirstResponder];
    }else
    {
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        mMoreView = [MoreInputView moreInputView];
        mMoreView.backgroundColor = [UIColor lightGrayColor];
        mMoreView.delegate = self;
        [self addSubview:mMoreView];
        mMoreView.translatesAutoresizingMaskIntoConstraints  = NO;
        NSDictionary *metrics = @{@"bottomToInputView":@kDefaultBottomTextView_SupView};
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[emojiView]-0-|" options:0 metrics:nil views:@{@"emojiView":mMoreView}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[inputView]-bottomToInputView-[emojiView]" options:0 metrics:metrics views:@{@"emojiView":mMoreView,@"inputView":self.inputView}]];
        
        mBottomConstraintTextView.constant = (kDefaultBottomTextView_SupView+[mMoreView intrinsicContentSize].height);
        [self.inputView resignFirstResponder];
          [CATransaction commit];
        [self invalidateIntrinsicContentSize];
        
        sender.selected = !sender.selected;
    }
  
}
#pragma mark -- emojiView delegate
-(void)emojiViewDidSelectedEmotion:(EmojiEmotion *)emotion{
    [self.inputView insertEmojiEmotion:emotion];
}
-(void)emojiViewDidDeleteAction{
    [self.inputView deleteBackward];
}
-(void)emojiViewDidSendAction{
    [self removeEmojiView];
    [self sendMessage];
}
#pragma mark -- 发送文字
-(void)sendMessage{
    NSAttributedString *attrText = self.inputView.attributedText;
    if(attrText.length <= 0){
//        [MBProgressHUD showTipMessage:NSLocalizedString(@"发送内容不能为空", nil)];
        
        return;
    }
    self.inputView.attributedText = nil;
    [self textViewDidChange:self.inputView];
    if([self.delegate respondsToSelector:@selector(inputView:didSendText:)]){
        [self.delegate inputView:self didSendText:attrText];
    }

}
#pragma mark -- MoreInputViewDelegate
-(void)moreInputViewDidFinshSelectedImage:(UIImage *)image imageURL:(NSURL *)imageURL{
    if([self.delegate respondsToSelector:@selector(inputView:didSendImage:imageURL:)]){
        [self.delegate inputView:self didSendImage:image imageURL:imageURL];
    }
    
//    if (mMoreView)
//    {//如果当前还在显示更多视图，则隐藏他先
//        [self moreAction:self.moreBtn];
//    }
//    [self removeMoreView];
}
#pragma mark -- VoiceRecordDelegate
-(void)voiceRecordFinshRecord:(NSString *)recordPath recordData:(NSData *)recordData duration:(CGFloat)duration{
    [self removeVoiceView];
    if([self.delegate respondsToSelector:@selector(inputView:didSendVoice:length:path:)]){
        [self.delegate inputView:self didSendVoice:recordData length:duration path:recordPath];
    }
}

@end
